package com.weixing.mall.util;

import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: mall-master
 * @description: list工具类
 * @author: wangfang
 * @create: 2021-11-11 10:51
 **/

public class ListUtil {

    public static  final  Integer SIZE=100;

    /**
     * 将一组数据平均分成n组
     *
     * @param source 要分组的数据源
     * @param n      平均分成n组
     * @param <T> 构造型
     * @return 返回list集合
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<>();
        int remainder = source.size() % n;  //(计算出余数)
        int number = source.size() / n;  //商
        int offset = 0;//偏移量
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            if (remainder > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remainder--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }
    /**
     * 将一组数据固定分组，每组n个元素
     * @param source 要分组的数据源
     * @param n      每组n个元素
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> fixedGrouping(List<T> source, int n) {

        if (null == source || source.size() == 0 || n <= 0)
            return null;
        List<List<T>> result = new ArrayList<List<T>>();

        int sourceSize = source.size();
        int size = (source.size() / n) + 1;
        for (int i = 0; i < size; i++) {
            List<T> subset = new ArrayList<T>();
            for (int j = i * n; j < (i + 1) * n; j++) {
                if (j < sourceSize) {
                    subset.add(source.get(j));
                }
            }
            if (!CollectionUtils.isEmpty(subset)){
                result.add(subset);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<String> tt= Lists.newArrayList();
        for(int i=0;i<125;i++){
            tt.add(String.valueOf(i));
        }
        List<List<String>> tt2=fixedGrouping(tt,300);
        for(List<String> list:tt2){
            for(String ss:list){
                System.out.println(ss);
            }
        }

    }
}
